package com.elias.share.controller;

import cn.hutool.core.io.unit.DataSizeUtil;
import com.elias.share.service.IFileService;
import com.elias.share.utils.InstantUtil;
import com.elias.share.vo.WebResultVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.nio.file.Paths;
import java.time.Instant;

@Validated
@Log4j2
@RequestMapping("file")
@RestController
public class FileController {

    @Resource
    private IFileService fileService;

    @PostMapping("/upload/{time}")
    public WebResultVo<String> uploadFile(@RequestParam("file") @NotNull MultipartFile file,
                                          @PathVariable("time") @NotNull Integer expireTime) {
        Instant start = Instant.now();
        log.info("uploading file start,name:{},size:{}", file.getOriginalFilename(), DataSizeUtil.format(file.getSize()));
        WebResultVo<String> resultVo = fileService.uploadFile(file, expireTime);
        log.info("upload end,name:{},time:{}ms,result:{}", file.getOriginalFilename(), InstantUtil.calcIntervalMilis(start), resultVo);
        return resultVo;
    }

    @GetMapping("/download/{month}/{day}/{hour}/{fileName}")
    public void downloadFile(@PathVariable("fileName") @NotNull String fileName,
                             @PathVariable("month") @NotNull @Min(1) @Max(12) Integer month,
                             @PathVariable("day") @NotNull @Min(1) @Max(31) Integer day,
                             @PathVariable("hour") @NotNull @Min(0) @Max(23) Integer hour,
                             HttpServletResponse response) {
        fileService.downloadFile(Paths.get(String.valueOf(month), String.valueOf(day), String.valueOf(hour), fileName), response);
    }
}
